package com.erp.config;

import com.alibaba.fastjson.JSON;
import com.erp.annotation.Permission;
import com.erp.controller.UserController;
import com.erp.dto.TokenData;
import com.erp.pojo.Roler;
import com.erp.service.RolerService;
import com.erp.service.UserRoleService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Aspect
@Component
@Order(200)
public class PressionAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;
    @Autowired
    private RolerService rolerService;
    @Autowired
    private UserRoleService userRoleService;


    @Around("@annotation(com.erp.annotation.Permission)")
    public Object checkRole(ProceedingJoinPoint joinPoint) throws Throwable {
        String requestURL = request.getRequestURI();
        String auth = request.getHeader("authorization");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Permission permission = method.getAnnotation(Permission.class);
        String role = permission.role();
        TokenData tokenData = UserController.map.get(auth);

        // 从 joinPoint 中获取方法参数并转换为 JSON 字符串
        Object[] args = joinPoint.getArgs();
        String requestDataJson = com.alibaba.fastjson.JSON.toJSONString(args);

        List<Roler> rolers = rolerService.queryUserRoleList(tokenData.getUserId());

        List<String> rolerNames = rolers.stream().map(Roler::getRname).collect(Collectors.toList());
        if(rolerNames.contains("超级管理员")){
             return joinPoint.proceed();
        } else {
            if (!rolerNames.contains(role)) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", 4031);
                map.put("message", "没有权限访问");
                response.getWriter().print(JSON.toJSONString(map));
                return null;
            }
        }
                 return joinPoint.proceed();
    }


}